import VueResource from 'vue-resource';
import { Loading } from 'element-ui';
import constant from './constant';

var _vue = {};
var loading = null;

function _Http(opts) {

  //如果没有域名默认配置baseURI
  if (!/^https?:\/\//i.test(opts.url) && !/^\/\//.test(opts.url)) {
    opts.url = constant.baseURI + opts.url;
  }

  if (opts.body) {
    try {
      var object = JSON.parse(opts.body);
      opts.body = JSON.stringify(object);
    } catch (e) {

    }
  } else if (opts.data) {
    opts.data = opts.data || {};
  }

  opts.headers = opts.headers || {};

  var userInfo = {};
  try{
    userInfo = JSON.parse(sessionStorage.getItem("UserInfo")) || {};
  }catch(e){}

  opts.headers["session-key"] = userInfo["sessionKey"] || userInfo["session_key"] || userInfo["sessio-key"] || "";
  var Http = this.$http || _vue.http;
  Http(opts).then(res => {

    //console.log("Http", res);
    if (loading && opts.config) {
      loading.close();
    }
    if (res.body.code == 20002 || res.body.code == 20001) {
      location.href = "login.html";
      return;
    } else {
      initLoadingLayer()
    }
    opts.success && opts.success(res.body);

    opts.complete && opts.complete(res.body || res);
  }).catch(res => {
    console.log("Exception", res);
    initLoadingLayer()
    if (opts.reqCount < 2) {
      opts.reqCount++;
      _Http.call(this, opts);
    } else {
      if (loading) {
        loading.spinner = "el-icon-refresh";
        loading.text = "加载失败，点击以重新加载";
      }
      opts.error && opts.error(res);
      opts.complete && opts.complete(res);
    }
  });
}

function _http(opts) {
  opts.async = true;
  opts.timeout = 20000;
  if (loading && opts.config) loading.close();
  if (opts.config && opts.config.loading) {
    loading = Loading.service({ target: opts.config.target });
    var el = opts.config.target;
    el.onclick = function (ev) {
      var ev = ev || window.event;
      // var target = ev.target || ev.srcElement;
      if (opts.config.refresh && (ev.target.className == 'el-loading-mask' || ev.target.className == "el-loading-spinner" || ev.target.className == "el-icon-refresh")) {
        opts.config.refresh();
      }
    }
  }
  _Http.call(this, opts);
}

function Get(url, opts) {
  if (typeof url == "object") {
    opts = url;
    url = opts.url;
  }
  opts = opts || {};
  opts.url = url;
  opts.method = "get";
  opts.reqCount = 0;
  opts.params = opts.data;
  _http.call(this, opts);
}

function Post(url, opts) {
  if (typeof url == "object") {
    opts = url;
    url = opts.url;
  }
  opts = opts || {};
  opts.data = opts.data || {};
  if (typeof opts.data == "object") { 
    var data = [];
    for(var key in opts.data){
      if(!opts.data[key]) continue;
      data.push(key+"="+encodeURIComponent(opts.data[key]));
    }
    opts.data = data.join("&");
  }
  opts.url = url;
  opts.method = "post";
  opts.body = opts.data;
  opts.headers = opts.headers || {};
  opts.headers["Content-Type"] = 'application/x-www-form-urlencoded';
  opts.reqCount = 0;
  console.log(opts);
  _http.call(this, opts);
}

function PostStream(url, opts) {
  if (typeof url == "object") {
    opts = url;
    url = opts.url;
  }
  opts = opts || {};
  opts.data = opts.data || {};
  if (typeof opts.data == "object") { 
    opts.data = JSON.stringify(opts.data);
  }
  opts.url = url;
  opts.reqCount = 0;
  opts.method = "post";
  opts.body = opts.data;
  opts.headers = opts.headers || {};
  opts.headers["Content-Type"] = 'application/json;charset=utf-8';
  delete opts.data;
  _http.call(this, opts);
}

function PostFormData(url, opts) {
  if (typeof url == "object") {
    opts = url;
    url = opts.url;
  }
  opts = opts || {};
  opts.data = opts.data || {};
  var params = new FormData();
  if (typeof opts.data == "object") {
    for(var key in opts.data){
      params.append(key, opts.data[key])
    }
  }
  opts.url = url;
  opts.reqCount = 0;
  opts.method = "post";
  opts.body = params;
  opts.headers = opts.headers || {};
  opts.headers["Content-Type"] = 'application/x-www-form-urlencoded;charset=UTF-8';
  opts.emulateJSON = true;
  delete opts.data;
  _http.call(this, opts);
}

function ExportExcel(url, param) {

  //添加身份标识
  var userInfo = localStorage.getItem("UserInfo") || sessionStorage.getItem("UserInfo");
  var token = "";

  if (userInfo) {
    try {
      userInfo = JSON.parse(userInfo);
      token = userInfo.token;
    } catch (e) {}
  }

  param = param || {};
  param.token = param.token || token;
  //如果没有域名默认配置baseURI
  if (!/https?:\/\//i.test(url)) {
    url = constant.baseURI + url;
  }

  var paramArr = [];
  for (var key in param) {
    if (!param[key]) continue;
    if (typeof param[key] == 'object') {
      param[key] = encodeURIComponent(JSON.stringify(param[key]));
    }
    paramArr.push(key + "=" + param[key]);
  }
  if (paramArr.length != 0) {
    if (url.indexOf('?') >= 0) {
      url += "&";
    } else {
      url += "?";
    }
    url += paramArr.join("&");

    var saveLink = document.createElement('a');
    saveLink.href = url;
    saveLink.target = '_blank';
    saveLink.click();
  }
}

//初始化插件
function plugin(Vue) {
  if (plugin.installed) {
    return;
  }
  _vue = Vue;

  //引入resource插件
  Vue.use(VueResource);

  Vue.get = Get;
  Vue.post = Post;
  Vue.postStream = PostStream;
  Vue.postFormData = PostFormData;

  Object.defineProperties(Vue.prototype, {
    $get: {
      get: function get() {
        return Get;
      }
    },
    $post: {
      get: function get() {
        return Post;
      }
    },
    $postStream: {
      get: function get() {
        return PostStream;
      }
    },
    $exportExcel: {
      get: function get() {
        return ExportExcel;
      }
    },
    $postFormData: {
      get: function get() {
        return PostFormData;
      }
    },
  });
}

if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.use(plugin);
}

function initLoadingLayer() {
  // 这里判断如果是登录页就不做加载中的状态提示 [HOP 2018-05-15]
  var url = location.href
  if (url.indexOf('login.html') < 0 && url.indexOf('customize-center.html') < 0) {
    var $app = $('#app')
    if (!$app.is(':hidden')) {
      setTimeout(function() {
        $('#systemLoading').hide()
      }, 3000)
    }
  }
}

plugin.get = Get;
plugin.post = Post;
plugin.postStream = PostStream;
plugin.exportExcel = ExportExcel;
plugin.postFormData = PostFormData;


export default plugin;
